﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.DataVisualization.Charting;
using IndexMarkSilverlightClient.IndexMarkServiceReference;
using Section = IndexMarkSilverlightClient.IndexMarkServiceReference.Section;

namespace IndexMarkSilverlightClient.Views.Controls.ReportsControls
{
    public partial class AvgIndexes : UserControl, INotifyPropertyChanged
    {

        private IndexMarkServiceReference.IndexMarkServiceClient client = new IndexMarkServiceClient();

        private ObservableCollection<IndexRow> indexes = new ObservableCollection<IndexRow>();
        private List<KeyValuePair<string, double>> IndexesMain = new List<KeyValuePair<string, double>>();
        private List<KeyValuePair<string, double>> IndexesLider = new List<KeyValuePair<string, double>>();
        private List<KeyValuePair<string, double>> IndexesHarmon = new List<KeyValuePair<string, double>>();
        private int IDTerm = 6;
        bool depsloaded = false;
        bool facsloaded = false;
        bool positionloaded = false;
        bool sectionloaded = false;
        private bool indexloaded = false;

        private ObservableCollection<Department> _departments = new ObservableCollection<Department>();
        private ObservableCollection<Department> _faculties = new ObservableCollection<Department>();
        private ObservableCollection<Section> _section = new ObservableCollection<Section>();
        public ObservableCollection<Position> _positions = new ObservableCollection<Position>();
        IndexStrategyType StrategyType;

        private ObservableCollection<IndexRow> cache;

        public AvgIndexes(IndexStrategyType strategy = IndexStrategyType.PPS)
        {
            StrategyType = strategy;
            InitializeComponent();
            Loaded += new RoutedEventHandler(UserControl_Loaded);
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            client.GetIndexes2Completed += new EventHandler<GetIndexes2CompletedEventArgs>(client_GetIndexesCompleted);
            client.GetDepartmentsListCompleted += new EventHandler<GetDepartmentsListCompletedEventArgs>(getDepartmentListComplited);
            client.GetPositionListCompleted += new EventHandler<GetPositionListCompletedEventArgs>(client_GetPositionListCompleted);
            client.GetParentsSectionsCompleted += new EventHandler<GetParentsSectionsCompletedEventArgs>(client_GetParentsSectionsCompleted);
            //var vm = (((((((this.Parent as Grid).Parent as Grid).Parent as ReportsMain).Parent as Frame).Parent as Border).Parent as Grid).Parent as MainPage).ViewModel;            
            var vm = MainPage.ViewModel;
            vm.SelectTerm -= ViewModel_SelectTerm;
            vm.SelectTerm += new MainViewModel.SelectTermEventHandler(ViewModel_SelectTerm);
            vm.SelectTermInit();


            client.GetDepartmentsListAsync(IDTerm);
            client.GetPositionListAsync(IDTerm);
            client.GetParentsSectionsAsync(IDTerm);
            client.GetIndexes2Async(IDTerm, new ObservableCollection<int>(), new ObservableCollection<int>(), new ObservableCollection<int>(), IndexListType.Full, StrategyType);
            IndexesChart.Visibility = Visibility.Collapsed;
            TypeCB.Visibility = Visibility.Collapsed;
            DepsLB.Visibility = Visibility.Collapsed;
            loadingBar.Visibility = Visibility.Visible;
            txtBlock.Visibility = Visibility.Collapsed;

        }

        void client_GetParentsSectionsCompleted(object sender, GetParentsSectionsCompletedEventArgs e)
        {
            _section = e.Result;
            foreach (var s in _section)
                s.Check = true;

            if (TypeCB.SelectedIndex == 3) DepsLB.ItemsSource = _section;

            sectionloaded = true;
            allDataLoaded();
        }

        void client_GetPositionListCompleted(object sender, GetPositionListCompletedEventArgs e)
        {
            _positions = e.Result;
            foreach (var s in _positions)
                s.Check = true;

            if (TypeCB.SelectedIndex == 2) DepsLB.ItemsSource = _positions;
            positionloaded = true;
            allDataLoaded();

        }

        void getDepartmentListComplited(object sender, GetDepartmentsListCompletedEventArgs e)
        {

            var c = e.Result.Where(x => x.Type == "Кафедра");
            var f = e.Result.Where(x => x.Type == "Факультет");

            foreach (Department department in c)
            {
                department.Check = true;
                _departments.Add(department);
            }
            if (TypeCB.SelectedIndex == 0) DepsLB.ItemsSource = _departments;
            foreach (Department department in f)
            {
                department.Check = true;
                _faculties.Add(department);
            }
            if (TypeCB.SelectedIndex == 1) DepsLB.ItemsSource = _faculties;

            depsloaded = true;
            facsloaded = true;
            allDataLoaded();

        }

        void ViewModel_SelectTerm(object sender, Classes.SelectTermEventsArgs e)
        {
            //IDTerm = e.SelectTerm.IDTerm;
            //client.GetIndexes2Async(IDTerm, new ObservableCollection<int>(),
            //    new ObservableCollection<int>(), new ObservableCollection<int>(),
            //    IndexListType.Full, StrategyType);
        }

        void client_GetIndexesCompleted1(object sender, GetIndexes2CompletedEventArgs e)
        {
            cache = e.Result;
            indexes = cache;
            client_GetIndexesCompleted1(sender, e);
        }

        private void CalcIndexes()
        {
            IndexesMain.Clear();
            IndexesLider.Clear();
            IndexesHarmon.Clear();

            if (indexes.Count != 0)
            {
                if (TypeCB.SelectedIndex == 0) //группируем по кафедрам
                {
                    IndexesMain = (from Ind in indexes
                                   group Ind by new { Dep = Ind.Resp.Department.Abbriviation }
                                       into IndGroup
                                       select new KeyValuePair<string, double>(IndGroup.Key.Dep, (double)IndGroup.Average(x => x.Index))).ToList();

                    IndexesLider = (from Ind in indexes
                                    group Ind by new { Dep = Ind.Resp.Department.Abbriviation }
                                        into IndGroup
                                        select new KeyValuePair<string, double>(IndGroup.Key.Dep, (double)IndGroup.Average(x => x.IndexLider.Index))).ToList();

                    IndexesHarmon = (from Ind in indexes
                                     group Ind by new { Dep = Ind.Resp.Department }
                                         into IndGroup
                                         select new KeyValuePair<string, double>(IndGroup.Key.Dep.Abbriviation, (double)IndGroup.Average(x => x.IndexHarmony))).ToList();
                }
                if (TypeCB.SelectedIndex == 1) //группируем по факультетам
                {
                    IndexesMain = (from Ind in indexes
                                   group Ind by new { Dep = Ind.Resp.Department.Parent.Abbriviation }
                                       into IndGroup
                                       select new KeyValuePair<string, double>(IndGroup.Key.Dep, (double)IndGroup.Average(x => x.Index))).ToList();

                    IndexesLider = (from Ind in indexes
                                    group Ind by new { Dep = Ind.Resp.Department.Parent.Abbriviation }
                                        into IndGroup
                                        select new KeyValuePair<string, double>(IndGroup.Key.Dep, (double)IndGroup.Average(x => x.IndexLider.Index))).ToList();

                    IndexesHarmon = (from Ind in indexes
                                     group Ind by new { Dep = Ind.Resp.Department.Parent.Abbriviation }
                                         into IndGroup
                                         select new KeyValuePair<string, double>(IndGroup.Key.Dep, (double)IndGroup.Average(x => x.IndexHarmony))).ToList();
                }
                if (TypeCB.SelectedIndex == 2) //группируем по должностям
                {
                    IndexesMain = (from Ind in indexes
                                   group Ind by new { Pos = Ind.Position }
                                       into IndGroup
                                       select new KeyValuePair<string, double>(IndGroup.Key.Pos, (double)IndGroup.Average(x => x.Index))).ToList();

                    IndexesLider = (from Ind in indexes
                                    group Ind by new { Pos = Ind.Position }
                                        into IndGroup
                                        select new KeyValuePair<string, double>(IndGroup.Key.Pos, (double)IndGroup.Average(x => x.IndexLider.Index))).ToList();

                    IndexesHarmon = (from Ind in indexes
                                     group Ind by new { Pos = Ind.Position }
                                         into IndGroup
                                         select new KeyValuePair<string, double>(IndGroup.Key.Pos, (double)IndGroup.Average(x => x.IndexHarmony))).ToList();
                }
                if (TypeCB.SelectedIndex == 3) //группируем по разделам
                {
                    IndexesMain.Add(new KeyValuePair<string, double>("1", 0));
                    IndexesMain.Add(new KeyValuePair<string, double>("2", 0));
                    IndexesMain.Add(new KeyValuePair<string, double>("3", 0));
                    IndexesMain.Add(new KeyValuePair<string, double>("4", 0));
                    IndexesMain.Add(new KeyValuePair<string, double>("5", 0));
                    IndexesMain.Add(new KeyValuePair<string, double>("6", 0));
                    foreach (IndexRow row in indexes)
                    {
                        int i = 0;
                        foreach (SectionIndex SI in row.SectionIndex.Where(x => !x.Section.Contains(".") && x.Section != "7"))
                        {
                            IndexesMain[i] = new KeyValuePair<string, double>((i + 1).ToString(), IndexesMain[i].Value + SI.Index);
                            i++;
                        }
                    }
                    for (int i = 0; i < IndexesMain.Count; i++)
                    {
                        IndexesMain[i] = new KeyValuePair<string, double>(IndexesMain[i].Key, IndexesMain[i].Value / indexes.Count);
                    }
                }

                // IndexesChart.Visibility = Visibility.Visible;

                DrawIndexes(IndexesMain, IndexesLider, IndexesHarmon);


            }
        }

        void client_GetIndexesCompleted(object sender, GetIndexes2CompletedEventArgs e)
        {
            indexes = e.Result;
            indexloaded = true;
            allDataLoaded();
            return;

            indexes = e.Result;
            IndexesMain.Clear();
            IndexesLider.Clear();
            IndexesHarmon.Clear();


            if (TypeCB.SelectedIndex == 0) //группируем по кафедрам
            {
                IndexesMain = (from Ind in e.Result
                               group Ind by new { Dep = Ind.Resp.Department.Abbriviation }
                                   into IndGroup
                                   select new KeyValuePair<string, double>(IndGroup.Key.Dep, (double)IndGroup.Average(x => x.Index))).ToList();

                IndexesLider = (from Ind in e.Result
                                group Ind by new { Dep = Ind.Resp.Department.Abbriviation }
                                    into IndGroup
                                    select new KeyValuePair<string, double>(IndGroup.Key.Dep, (double)IndGroup.Average(x => x.IndexLider.Index))).ToList();

                IndexesHarmon = (from Ind in e.Result
                                 group Ind by new { Dep = Ind.Resp.Department }
                                     into IndGroup
                                     select new KeyValuePair<string, double>(IndGroup.Key.Dep.Abbriviation, (double)IndGroup.Average(x => x.IndexHarmony))).ToList();
            }
            if (TypeCB.SelectedIndex == 1) //группируем по факультетам
            {
                IndexesMain = (from Ind in e.Result
                               group Ind by new { Dep = Ind.Resp.Department.Parent.Abbriviation }
                                   into IndGroup
                                   select new KeyValuePair<string, double>(IndGroup.Key.Dep, (double)IndGroup.Average(x => x.Index))).ToList();

                IndexesLider = (from Ind in e.Result
                                group Ind by new { Dep = Ind.Resp.Department.Parent.Abbriviation }
                                    into IndGroup
                                    select new KeyValuePair<string, double>(IndGroup.Key.Dep, (double)IndGroup.Average(x => x.IndexLider.Index))).ToList();

                IndexesHarmon = (from Ind in e.Result
                                 group Ind by new { Dep = Ind.Resp.Department.Parent.Abbriviation }
                                     into IndGroup
                                     select new KeyValuePair<string, double>(IndGroup.Key.Dep, (double)IndGroup.Average(x => x.IndexHarmony))).ToList();
            }
            if (TypeCB.SelectedIndex == 2) //группируем по должностям
            {
                IndexesMain = (from Ind in e.Result
                               group Ind by new { Pos = Ind.Position }
                                   into IndGroup
                                   select new KeyValuePair<string, double>(IndGroup.Key.Pos, (double)IndGroup.Average(x => x.Index))).ToList();

                IndexesLider = (from Ind in e.Result
                                group Ind by new { Pos = Ind.Position }
                                    into IndGroup
                                    select new KeyValuePair<string, double>(IndGroup.Key.Pos, (double)IndGroup.Average(x => x.IndexLider.Index))).ToList();

                IndexesHarmon = (from Ind in e.Result
                                 group Ind by new { Pos = Ind.Position }
                                     into IndGroup
                                     select new KeyValuePair<string, double>(IndGroup.Key.Pos, (double)IndGroup.Average(x => x.IndexHarmony))).ToList();
            }
            if (TypeCB.SelectedIndex == 3) //группируем по разделам
            {
                IndexesMain.Add(new KeyValuePair<string, double>("1", 0));
                IndexesMain.Add(new KeyValuePair<string, double>("2", 0));
                IndexesMain.Add(new KeyValuePair<string, double>("3", 0));
                IndexesMain.Add(new KeyValuePair<string, double>("4", 0));
                IndexesMain.Add(new KeyValuePair<string, double>("5", 0));
                IndexesMain.Add(new KeyValuePair<string, double>("6", 0));
                foreach (IndexRow row in e.Result)
                {
                    int i = 0;
                    foreach (SectionIndex SI in row.SectionIndex.Where(x => !x.Section.Contains(".") && x.Section != "7"))
                    {
                        IndexesMain[i] = new KeyValuePair<string, double>((i + 1).ToString(), IndexesMain[i].Value + SI.Index);
                        i++;
                    }
                }
                for (int i = 0; i < IndexesMain.Count; i++)
                {
                    IndexesMain[i] = new KeyValuePair<string, double>(IndexesMain[i].Key, IndexesMain[i].Value / e.Result.Count);
                }
            }

            //   IndexesChart.Visibility = Visibility.Visible;

            DrawIndexes(IndexesMain, IndexesLider, IndexesHarmon);

        }

        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            //client.GetIndexes2Async(IDTerm, new ObservableCollection<int>(),
            //    new ObservableCollection<int>(), new ObservableCollection<int>(), 
            //    IndexListType.Full, StrategyType);
            allDataLoaded();

        }

        void allDataLoaded()
        {
            if (
                depsloaded
                && facsloaded
                && positionloaded
                && sectionloaded
                && indexloaded
                )
            {
                //MessageBox.Show("loaded");
                IndexesChart.Visibility = Visibility.Visible;
                TypeCB.Visibility = Visibility.Visible;
                DepsLB.Visibility = Visibility.Visible;
                txtBlock.Visibility = Visibility.Visible;
                CalcIndexes();
                loadingBar.Visibility = Visibility.Collapsed;

            }
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {


            int termIDENTITY = IDTerm; //заменить потом на term ID

            if ((sender as ComboBox).SelectedIndex == 0 && depsloaded) //выбраны кафедры
            {
                DepsLB.ItemsSource = _departments;
            }
            if ((sender as ComboBox).SelectedIndex == 1 && facsloaded) //выбраны факультеты
            {
                DepsLB.ItemsSource = _faculties;
            }
            if ((sender as ComboBox).SelectedIndex == 2 && positionloaded) //выбраны должности
            {
                DepsLB.ItemsSource = _positions;
            }
            if ((sender as ComboBox).SelectedIndex == 3 && sectionloaded) //выбраны разделы
            {
                DepsLB.ItemsSource = _section;
            }
            allDataLoaded();
        }

        public void DrawIndexes(List<KeyValuePair<string, double>> IndexesMain, List<KeyValuePair<string, double>> IndexesLider, List<KeyValuePair<string, double>> IndexesHarmon)
        {
            List<KeyValuePair<string, double>> MainIndexes = new List<KeyValuePair<string, double>>();
            List<KeyValuePair<string, double>> LiderIndexes = new List<KeyValuePair<string, double>>();
            List<KeyValuePair<string, double>> HarmonIndexes = new List<KeyValuePair<string, double>>();

            (IndexesChart.LegendItems[1] as LegendItem).Visibility = Visibility.Collapsed;
            (IndexesChart.LegendItems[2] as LegendItem).Visibility = Visibility.Collapsed;

            if (TypeCB.SelectedIndex == 0 && _departments.Count != 0)//
            {
                foreach (Department Cat in _departments)
                {

                    if (Cat.Check)
                    {
                        MainIndexes.Add(new KeyValuePair<string, double>(Cat.Abbriviation, IndexesMain.Where(x => x.Key == Cat.Abbriviation).FirstOrDefault().Value));
                        LiderIndexes.Add(new KeyValuePair<string, double>(Cat.Abbriviation, IndexesLider.Where(x => x.Key == Cat.Abbriviation).FirstOrDefault().Value));
                        HarmonIndexes.Add(new KeyValuePair<string, double>(Cat.Abbriviation, IndexesHarmon.Where(x => x.Key == Cat.Abbriviation).FirstOrDefault().Value));
                    }

                }
                (IndexesChart.LegendItems[1] as LegendItem).Visibility = Visibility.Visible;
                (IndexesChart.LegendItems[2] as LegendItem).Visibility = Visibility.Visible;
            }
            if (TypeCB.SelectedIndex == 1 && _faculties.Count != 0)//
            {
                foreach (Department Dep in _faculties)
                {

                    if (Dep.Check)
                    {
                        double a = IndexesMain.Where(x => x.Key == Dep.Abbriviation).SingleOrDefault().Value;
                        MainIndexes.Add(new KeyValuePair<string, double>(Dep.Abbriviation,
                                                                         IndexesMain.Where(x => x.Key == Dep.Abbriviation).
                                                                             FirstOrDefault().Value));
                        LiderIndexes.Add(new KeyValuePair<string, double>(Dep.Abbriviation,
                                                                          IndexesLider.Where(x => x.Key == Dep.Abbriviation)
                                                                              .FirstOrDefault().Value));
                        HarmonIndexes.Add(new KeyValuePair<string, double>(Dep.Abbriviation,
                                                                           IndexesHarmon.Where(
                                                                               x => x.Key == Dep.Abbriviation).
                                                                               FirstOrDefault().Value));
                    }


                }
                (IndexesChart.LegendItems[1] as LegendItem).Visibility = Visibility.Visible;
                (IndexesChart.LegendItems[2] as LegendItem).Visibility = Visibility.Visible;
            }
            if (TypeCB.SelectedIndex == 2 && _positions.Count != 0)
            {
                foreach (Position Pos in _positions)
                {
                    if (Pos.Check)
                    {
                        MainIndexes.Add(new KeyValuePair<string, double>(Pos.Name, IndexesMain.Where(x => x.Key == Pos.Name).SingleOrDefault().Value));
                        LiderIndexes.Add(new KeyValuePair<string, double>(Pos.Name, IndexesLider.Where(x => x.Key == Pos.Name).SingleOrDefault().Value));
                        HarmonIndexes.Add(new KeyValuePair<string, double>(Pos.Name, IndexesHarmon.Where(x => x.Key == Pos.Name).SingleOrDefault().Value));
                    }
                }
                (IndexesChart.LegendItems[1] as LegendItem).Visibility = Visibility.Visible;
                (IndexesChart.LegendItems[2] as LegendItem).Visibility = Visibility.Visible;
            }
            if (TypeCB.SelectedIndex == 3)
            {
                foreach (Section Sec in _section)
                {
                    if (Sec.Check)
                        MainIndexes.Add(new KeyValuePair<string, double>(Sec.Order, IndexesMain.Where(x => x.Key == Sec.Order).SingleOrDefault().Value));
                }

                //(IndexesChart.LegendItems[1] as LegendItem).Visibility = Visibility.Collapsed;
                //(IndexesChart.LegendItems[2] as LegendItem).Visibility = Visibility.Collapsed;

            }

            (IndexesChart.Series[0] as ColumnSeries).ItemsSource = MainIndexes;
            (IndexesChart.Series[1] as ColumnSeries).ItemsSource = LiderIndexes;
            (IndexesChart.Series[2] as ColumnSeries).ItemsSource = HarmonIndexes;

            //   IndexesChart.Visibility = System.Windows.Visibility.Visible; 
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}